const jwt = require('jsonwebtoken')
const { JWT_SECRET } = require('../config/config.default')

const authCheck = async (ctx, next) => {
  const token = ctx.headers.authorization?.replace('Bearer ', '');
  if(token) {
    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      ctx.state.user = decoded;
      ctx.state.token = token;
    } catch (err) {
      ctx.state.user = {};
      // if (err.name === 'TokenExpiredError') {
      //   ctx.status = 401;
      //   ctx.body = { code: 401, message: '登录已过期，请重新登录' };
      //   return;
      // }
      // throw err;
    }
  }
  await next();
}
module.exports = authCheck;
